package com.example.mystoryapp2.ui.main.fragments

import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mystoryapp2.R
import com.example.mystoryapp2.databinding.FragmentReaderHomeBinding
import com.example.mystoryapp2.domain.Story
import com.example.mystoryapp2.ui.base.BaseFragment
import com.example.mystoryapp2.ui.base.BaseListAdapter
import com.example.mystoryapp2.ui.story.StoryDescriptionActivity

class ReaderHomeFragment : BaseFragment<FragmentReaderHomeBinding>() {

    companion object {
        fun newInstance() = ReaderHomeFragment()
    }

    private lateinit var viewModel: ReaderHomeViewModel

    override fun getLayoutId(): Int {
        return R.layout.fragment_reader_home
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this)[ReaderHomeViewModel::class.java]
        mDataBinding.viewModel = viewModel
        val layoutManager = LinearLayoutManager(
            context, LinearLayoutManager.VERTICAL,
            false
        )
        mDataBinding.rv.layoutManager = layoutManager
        mDataBinding.btnSearch.setOnClickListener {
            search()
        }

        mDataBinding.viewModel?.storyAdapter?.value?.setClickListener(object :
            BaseListAdapter.IClickListener<Story> {
            override fun onClick(view: View, item: Story) {
                item.getStoryId()?.let { context?.let { it1 ->
                    StoryDescriptionActivity.start(it1, it) } }
            }
        })
        Handler().post({
            if(viewModel.categoryStrList.isNotEmpty()){
                Log.d("xqj", "onActivityCreated: 选择选项"+(viewModel.categoryStrList.size-1) )
                mDataBinding.spCategory.setSelection(viewModel.categoryStrList.size-1)
            }
        })

    }

    override fun onInitView(view: View) {

    }

    private fun search() {
        viewModel.search()
    }

}